/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.expert.web;

import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.utils.CacheUtils;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.Customer;
import com.chlitina.store.modules.base.entity.CustomerEmployeeRelationship;
import com.chlitina.store.modules.base.service.CustomerEmployeeRelationshipService;
import com.chlitina.store.modules.base.service.CustomerService;
import com.chlitina.store.modules.cash.service.StoreConsumeService;
import com.chlitina.store.modules.employee.entity.Employee;
import com.chlitina.store.modules.employee.service.EmployeeService;
import com.chlitina.store.modules.expert.entity.CustomerExam;
import com.chlitina.store.modules.expert.entity.CustomerExamParameters;
import com.chlitina.store.modules.expert.entity.CustomerSolution;
import com.chlitina.store.modules.expert.entity.ExpertExperienceBasic;
import com.chlitina.store.modules.expert.entity.ExpertExperienceProblemSolution;
import com.chlitina.store.modules.expert.entity.ExpertExperienceProblemSolutionDetail;
import com.chlitina.store.modules.expert.entity.Parameter;
import com.chlitina.store.modules.expert.entity.ParameterCategory;
import com.chlitina.store.modules.expert.entity.SolutionFace;
import com.chlitina.store.modules.expert.service.CustomerExamParametersService;
import com.chlitina.store.modules.expert.service.CustomerExamService;
import com.chlitina.store.modules.expert.service.ExpertExperienceBasicService;
import com.chlitina.store.modules.expert.service.ExpertExperienceProblemSolutionService;
import com.chlitina.store.modules.expert.service.ParameterCategoryService;
import com.chlitina.store.modules.expert.service.ParameterService;
import com.chlitina.store.modules.expert.service.SystemDefinitionAreaSeasonService;
import com.chlitina.store.modules.expert.utils.ExpertUtils;
import com.chlitina.store.modules.sms.quartz.CustomerTipQueueGenerate;
import com.chlitina.store.modules.sys.entity.Area;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

/**
 * 客户治疗信息Controller
 * @author lvbo
 * @version 2013-06-18
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH+"/expert/customerExam")
@SessionAttributes("examDetailTarget")
public class CustomerExamController extends BaseController {
	public static final String SESSION_FLITER_CUSTOMER = "session_fliter_customer";
	public static final String SESSION_SOLUTION = "session_solution";
	public static final String SESSION_NOT_ACTIVE = "session_not_active";
	public static final String DELETE_TARGET_SOLUTION = "solution";
	public static final String DELETE_TARGET_NOTACTIVE = "notActive";
	@Autowired
	private CustomerExamService customerExamService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private EmployeeService employeeService;
	@Autowired
	private ParameterCategoryService parameterCategoryService;
	@Autowired
	private ParameterService parameterService;
	@Autowired
	private ExpertExperienceBasicService expertExperienceBasicService;
	@Autowired
	private SystemDefinitionAreaSeasonService systemDefinitionAreaSeasonService;
	@Autowired
	private CustomerExamParametersService customerExamParametersService;
	@Autowired
	private ExpertExperienceProblemSolutionService expertExperienceProblemSolutionService;
	@Autowired
	private CustomerTipQueueGenerate customerTipQueueGenerate;
	@Autowired
	private CustomerEmployeeRelationshipService customerEmployeeRelationshipService;
	@Autowired
	private StoreConsumeService storeConsumeService;
	
	@ModelAttribute
	public CustomerExam get(@RequestParam(required=false) Long id) {
		if (id != null){
			return customerExamService.get(id);
		}else{
			return new CustomerExam();
		}
	}
	
	@RequestMapping(value = {"list", ""})
	public String list(@RequestParam(required=false)String currentSelectId, CustomerExam customerExam, HttpServletRequest request, HttpServletResponse response, Model model) {
		Long customerId = (Long)request.getSession().getAttribute("customerId");
		boolean justShowToday = false;
		if (customerId != null) {
			Page<CustomerExam> page = customerExamService.find(new Page<CustomerExam>(request, response), customerExam, customerId, null, null, justShowToday); 
			List<CustomerExam> list = page.getList();
			Map<Long, Integer> map = new HashMap<Long, Integer>();
			for (CustomerExam c : list) {
				long id = c.getId();
				if(c.getCustomerSolutionList().size() > 0) {
					map.put(id, 0);
				} else {
					Date show = c.getShow_time();
					Date now = new Date();
					if(show.getTime() < now.getTime()) {
						map.put(id, 1);
					} else {
						map.put(id, 2);
					}
				}
			}
			model.addAttribute("showMap", map);
			model.addAttribute("currentSelectId", currentSelectId);
			model.addAttribute("page", page);
		}
		return "modules/base/customerExamList";
	}
	
	@RequestMapping(value = "resultList")
	public String resultList(@RequestParam(required=false)String currentSelectId, CustomerExam customerExam, HttpServletRequest request, HttpServletResponse response, Model model) {
		String type = request.getParameter("searchType");
		String keyWord = request.getParameter("keyWord");
		boolean justShowToday = false;
		String today = request.getParameter("today");
		if(StringUtils.isNotEmpty(today)) {
			justShowToday = Boolean.valueOf(today);
		}
		Page<CustomerExam> page = new Page<CustomerExam>(request, response);
		Page<CustomerExam> current_page = customerExamService.find(page, customerExam, null, type, keyWord, justShowToday); 
		model.addAttribute("page", current_page);
		List<CustomerExam> list = current_page.getList();
		Map<Long, Integer> map = new HashMap<Long, Integer>();
		for (CustomerExam c : list) {
			long id = c.getId();
			if(c.getCustomerSolutionList().size() > 0) {
				map.put(id, 0);
			} else {
				Date show = c.getShow_time();
				Date now = new Date();
				if(show.getTime() < now.getTime()) {
					map.put(id, 1);
				} else {
					map.put(id, 2);
				}
			}
		} 
		model.addAttribute("keyWord", keyWord);
		model.addAttribute("searchType", type);
		model.addAttribute("showMap", map);
		model.addAttribute("currentSelectId", currentSelectId);
		return "modules/expert/customerExamResultList";
	}
	
	@RequestMapping(value = "customerList")
	public String customerList(CustomerExam customerExam, HttpServletRequest request, HttpServletResponse response, Model model) {
		String searchName = request.getParameter("searchName");
		Page<CustomerExam> page = new Page<CustomerExam>(request, response);
		Page<CustomerExam> current_page = customerExamService.findOngoingSolution(page, customerExam, searchName); 
		model.addAttribute("searchName", searchName);
		model.addAttribute("page", current_page);
		return "modules/expert/customerExamOngoingResultList";
	}
	
	@RequestMapping(value = "parameterSelect")
	public String parameterSelect(Long customer_id, Model model) {
		Customer customer = customerService.get(customer_id);
		model.addAttribute("customer", customer);
		List<ParameterCategory> list = parameterCategoryService.findAll();
		model.addAttribute("pList", list);
		return "modules/expert/customerExamSearch";
	}
	
	@RequestMapping(value = "form")
	public String form(CustomerExam customerExam, Model model) {
		model.addAttribute("customerExam", customerExam);
		return "modules/expert/customerExamForm";
	}
	
	@RequestMapping(value = "detail")
	public String detail(CustomerExam customerExam, Model model) {
		CacheUtils.put("customerExam_id", customerExam.getId());
		model.addAttribute("customerExam", customerExam);
		List<CustomerExamParameters> customerExamParametersList = customerExamParametersService.getByExamID(customerExam.getId());
		model.addAttribute("parametersList", customerExamParametersList);
		return "modules/expert/customerExamDetail";
	}

	@RequestMapping(value = "save")
	public String save(Long customer_id, Long employee_id,
			String ids, CustomerExam customerExam, Model model, RedirectAttributes redirectAttributes) {
		Customer customer = customerService.get(customer_id);
		Employee employee =employeeService.get(employee_id);
		customerExam.setStore(StoreUtils.getStore());
		customerExam.setCustomer(customer);
		customerExam.setEmployee(employee);
		customerExam.setExam_time(new Date());
		String [] parameterIdArray = ids.split(";");
		for (int i = 0; i < parameterIdArray.length; i++) {
			String id = parameterIdArray[i];
			if(id.equals("") || id.equals(";")) {
				continue;
			}
			Long pId = Long.parseLong(id);
			Parameter p = parameterService.get(pId);
			CustomerExamParameters c = new CustomerExamParameters();
			c.setCustomerExam(customerExam);
			c.setParameter(p);
			customerExam.getExamParametersList().add(c);
		}
		Calendar cal = Calendar.getInstance();
		int waitTime = (int) (25+ (Math.random()*5));
		cal.add(Calendar.SECOND, waitTime);
		customerExam.setShow_time(cal.getTime());
		customerExamService.save(customerExam);
		Long ceid = customerExam.getId();
		
		return "redirect:"+Global.ADMIN_PATH+"/base/customer/search?show=true&showTime=" + waitTime + "&id=" + customer.getId() + "&ceid=" + ceid;
	}

	@RequestMapping(value = "search")
	public String search(CustomerExam customerExam, HttpServletRequest request, HttpServletResponse response, Model model) {
		searchList(customerExam, model);
		model.addAttribute("exam_id", customerExam.getId());
		return "modules/expert/customerExamResult";
	}
	
	public void searchList(CustomerExam customerExam, Model model) {
		List<Map<String, Object>> mapList = Lists.newArrayList();
		Store store = customerExam.getCustomer().getStore();
		Area area = store.getArea();
		Long location = ExpertUtils.getFirstArea(area).getId();
		Long locationSeason = systemDefinitionAreaSeasonService.getTodayByArea(location);
		List<CustomerExamParameters> examParametersList = customerExam.getExamParametersList();
		Long [] parameterIdArray = new Long[examParametersList.size()];
		for (int i = 0; i < examParametersList.size(); i++) {
			parameterIdArray[i] = examParametersList.get(i).getParameter().getId();
		}
		int allWeight = (int) parameterService.getSumWeightByIds(parameterIdArray);
		List<ExpertExperienceBasic> expertExperienceBasicList = expertExperienceBasicService.getMiddle(allWeight);
		boolean ifHaveBasic = false;
		if(expertExperienceBasicList != null && expertExperienceBasicList.size() > 0) {
			for (ExpertExperienceBasic p : expertExperienceBasicList) {
				SolutionFace basic = p.getSolutionFace();
				Map<String, Object> map = Maps.newHashMap();
				map.put("priority", 0);
				map.put("SolutionFace", basic);
				map.put("skinType", p.getSkin_type());
				mapList.add(map);
				ifHaveBasic = true;
			}
		}
		List<ExpertExperienceProblemSolution> list = expertExperienceProblemSolutionService.getByParameters(parameterIdArray);
		for (ExpertExperienceProblemSolution p : list) {
			if(p.getStatus() == ExpertExperienceProblemSolution.FLAG_DISABLE) {
				continue;
			}
			SolutionFace e = p.getSolutionFace();
			Map<String, Object> map = Maps.newHashMap();
			map.put("priority", p.getPriority());
			map.put("SolutionFace", e);
			map.put("skinType", e.getSkinType());
			mapList.add(map);
		}
		
		@SuppressWarnings("unchecked")
		List<Map<String, Object>> dataList = ExpertUtils.getSearchJsonData(ifHaveBasic, mapList, locationSeason);
		List<String> solutionNameList = Lists.newArrayList();
		for (Map<String, Object> map : dataList) {
			solutionNameList.add((String)map.get("skinType"));
		}
		List<String> parameterList = Lists.newArrayList();
		for (int i = 0; i < parameterIdArray.length; i++) {
			parameterList.add(parameterService.get(parameterIdArray[i]).getName());
		}
		Map<String, String> map = ExpertUtils.getSolutionPriority();
		model.addAttribute("solutionPriority", map);
		model.addAttribute("parameterList", parameterList);
		model.addAttribute("solutionNameList", solutionNameList);
		model.addAttribute("customer", customerExam.getCustomer().getName());
		model.addAttribute("jsonData", JsonMapper.getInstance().toJson(dataList));
	}
	
	@RequestMapping(value = "customer")
	public String customer(HttpServletRequest request, HttpServletResponse response, Model model) {
		HttpSession session = request.getSession();
		@SuppressWarnings("unchecked")
		List<Customer> list = (List<Customer>)session.getAttribute(SESSION_FLITER_CUSTOMER);
		if (list != null) {
			if (list.size() > 0) {
				model.addAttribute("customerList", list);
			} else {
				addMessage(model, "不存在符合条件的客户！");
			}
		}
		return "modules/expert/customerExamCustomer";
	}
	
	@ResponseBody
	@RequestMapping(value = "deleteCustomer")
	public String deleteCustomer(HttpServletRequest request, HttpServletResponse response, Model model) {
		HttpSession session = request.getSession();
		String cid = request.getParameter("customerId");
		String target = request.getParameter("target");
		Long longId = null;
		try {
			longId = Long.parseLong(cid);
		} catch (Exception e) {
			return "";
		}
		if (DELETE_TARGET_NOTACTIVE.equals(target)) {
			updateCustomerListSession(session, SESSION_NOT_ACTIVE, longId);
		} else if (DELETE_TARGET_SOLUTION.equals(target)) {
			updateCustomerListSession(session, SESSION_FLITER_CUSTOMER, longId);
		}
		return "";
	}
	
	private void updateCustomerListSession(HttpSession session, String sessionStr, Long customerId){
		@SuppressWarnings("unchecked")
		List<Customer> list = (List<Customer>)session.getAttribute(sessionStr);
		List<Customer> afterList = Lists.newArrayList();
		if (list != null) {
			for (Customer customer : list) {
				if (customer != null && !customer.getId().equals(customerId)) {
					afterList.add(customer);
				}
			}
		}
		session.setAttribute(sessionStr, afterList);
	}
	
	@RequestMapping(value = "customerNotActive")
	public String customerNotActive(HttpServletRequest request, HttpServletResponse response, Model model) {
		HttpSession session = request.getSession();
		@SuppressWarnings("unchecked")
		List<Customer> list = (List<Customer>)session.getAttribute(SESSION_NOT_ACTIVE);
		if (list != null) {
			if (list.size() > 0) {
				model.addAttribute("customerList", list);
			} else {
				addMessage(model, "不存在符合条件的客户！");
			}
		}
		return "modules/expert/customerNotActive";
	}
	@RequestMapping(value = "filterCustomers")
	public String filterCustomer(HttpServletRequest request, HttpServletResponse response, Model model) {
		HttpSession session = request.getSession();
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String type = request.getParameter("type");
		String money = request.getParameter("maxMoney");
		String times = request.getParameter("maxTimes");
		String oldStart = (String)session.getAttribute("startDate");
		String oldEnd = (String)session.getAttribute("endDate");
		String oldType = (String)session.getAttribute("type");
		String oldMoney = (String)session.getAttribute("maxMoney");
		String oldTimes = (String)session.getAttribute("maxTimes");
		startDate = startDate != null ? startDate : oldStart;
		endDate = endDate != null ? endDate : oldEnd;
		type = type != null ? type : oldType;
		money = money != null ? money : oldMoney;
		times = times != null ? times : oldTimes;
		int number = 0;
		if ("times".equals(type)) {
			try {
				number = Integer.parseInt(times);
			} catch (NumberFormatException e) {
				number = 0;
			}
		}
		if ("money".equals(type)) {
			try {
				number = Integer.parseInt(money);
			} catch (NumberFormatException e) {
				number = 0;
			}
		}
		List<Customer> customerList = storeConsumeService.findByParameter(startDate, endDate, type, number);
		
		session.setAttribute("startDate", startDate);
		session.setAttribute("endDate", endDate);
		session.setAttribute("type", type);
		session.setAttribute("maxMoney", money);
		session.setAttribute("maxTimes", times);
		session.setAttribute(SESSION_NOT_ACTIVE, customerList);
		model.addAttribute("customerList", customerList);
		return "redirect:" + Global.ADMIN_PATH
				+ "/expert/customerExam/customerNotActive";
	}
	
	
	//通过方案查找符合用户，过滤已使用此方案用户
	@RequestMapping(value = "getCustomers")
	public String getCustomers(long solution_id, HttpServletRequest request, HttpServletResponse response, Model model) {
		HttpSession session = request.getSession();
		Store store = StoreUtils.getStore();
		long store_id = store.getId();
		List<ExpertExperienceBasic> basicList = expertExperienceBasicService.getBySolution(solution_id);
		List<ExpertExperienceProblemSolution> expertList = expertExperienceProblemSolutionService.getBySolutionId(solution_id);
		List<Long> examIds= customerExamService.getMaxIDsByStore(store_id);
		List<Customer> customerList = Lists.newArrayList();
		for (Long examId : examIds) {
			boolean ifChecked = false;
			CustomerExam exam = customerExamService.get(examId);
			Customer customer = exam.getCustomer();
			//过滤已使用此方案用户
			boolean ifUsed = false;
			List<CustomerSolution> 	clist = exam.getCustomerSolutionList();
			for (CustomerSolution customerSolution : clist) {
				if(customerSolution.getSolutionFace().getId() == solution_id 
						&& customerSolution.getStatus() == CustomerSolution.PROCEED_STATUS) {
					ifUsed = true;
					break;
				}
			}
			if(ifUsed) {
				continue;
			}
			int customerWeight = 0;
			List<Parameter> examParameters = Lists.newArrayList(); 
			List<CustomerExamParameters> list = customerExamParametersService.getByExamID(examId);
			for (CustomerExamParameters customerExamParameters : list) {
				Parameter parameter = customerExamParameters.getParameter();
				examParameters.add(parameter);
				customerWeight += parameter.getWeight();
			}
			
			for (ExpertExperienceProblemSolution e : expertList) {
				boolean ifAll = true;
				List<ExpertExperienceProblemSolutionDetail> detailList = e.getDetailList();
				for (ExpertExperienceProblemSolutionDetail expertExperienceProblemSolutionDetail : detailList) {
					Parameter parameter = expertExperienceProblemSolutionDetail.getParameter();
					if(!examParameters.contains(parameter)) {
						ifAll = false;
						break;
					}
				}
				if(ifAll) {
					ifChecked = true;
					break;	
				}
			}
			
			if(!ifChecked) {
				for (ExpertExperienceBasic e : basicList) {
					if(customerWeight >= e.getMin_value() && customerWeight <= e.getMax_value()) {
						ifChecked = true;
						break;
					}
				}	
			}
			if(ifChecked) {
				customerList.add(customer);
			}
		}
		//添加到session
		session.setAttribute(SESSION_SOLUTION, solution_id);
		session.setAttribute(SESSION_FLITER_CUSTOMER, customerList);
		return "redirect:" + Global.ADMIN_PATH
				+ "/expert/customerExam/customer";
	}
	
	@ResponseBody
	@RequestMapping(value = "getCustomerData")
	public String getCustomerData(@RequestParam(required=true) Long employeeId, HttpServletResponse response, HttpServletRequest request) {
		response.setContentType("application/json; charset=UTF-8");
		Map<Long, String> customerMap = Maps.newLinkedHashMap();
		List<CustomerEmployeeRelationship> cerList = customerEmployeeRelationshipService.findByEmployee(employeeId);
		if(cerList != null){
			for (CustomerEmployeeRelationship cer : cerList) {
				Customer c = cer.getCustomer();
				customerMap.put(c.getId(), c.getName() + "(" + c.getMobile() + ")");
			}
		}
		return JsonMapper.getInstance().toJson(customerMap);
	}
	
	@RequestMapping(value = "detailResult")
	public String detailResult(CustomerExam customerExam, HttpServletRequest request, HttpServletResponse response,  Model model) {
		List<Map<String, Object>> list = ExpertUtils.getCustomerSolutionMapData(customerExam);
		model.addAttribute("jsonData", JsonMapper.getInstance().toJson(list));
		model.addAttribute("customerExamId", customerExam.getId());
		return "modules/expert/detailTemplate";
	}
}
